package org.stvd.common.security.support;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;

public class StvdRequestMatcher implements RequestMatcher {

    /**
     * 需要排除的url列表
     */
    private List<String> execludeUrls;

    public List<String> getExecludeUrls() {
        return execludeUrls;
    }

    public void setExecludeUrls(List<String> execludeUrls) {
        this.execludeUrls = execludeUrls;
    }
    
    /**
     * 需要指定匹配的url列表，为空则匹配全部
     */
    private List<String> includeUrls;

    public List<String> getIncludeUrls() {
        return includeUrls;
    }

    public void setIncludeUrls(List<String> includeUrls) {
        this.includeUrls = includeUrls;
    }
    
    /**
     * 需要指定匹配允许的方法，为空则匹配全部
     */
    private List<String> notAllowedMethods;

    public List<String> getNotAllowedMethods() {
        return notAllowedMethods;
    }

    public void setNotAllowedMethods(List<String> notAllowedMethods) {
        this.notAllowedMethods = notAllowedMethods;
    }
    
    
    public StvdRequestMatcher() {
        notAllowedMethods = new ArrayList<String>();
        notAllowedMethods.add("GET");
        notAllowedMethods.add("HEAD");
        notAllowedMethods.add("TRACE");
        notAllowedMethods.add("OPTIONS");
    }
    
    public boolean matches(HttpServletRequest request) {

        PathMatcher pathMatcher = new AntPathMatcher();
        String path = request.getServletPath();
        
        boolean bMatched = true;
        //需要匹配的url列表
        if (includeUrls != null && includeUrls.size() > 0) {
            for (String url : includeUrls) {
                if (!pathMatcher.match(url, path)) {
                    bMatched = true;
                }
            }
        } else {
            bMatched = true;
        }
        
        //需要排除的url列表
        if (bMatched && execludeUrls != null && execludeUrls.size() > 0) {
            for (String url : execludeUrls) {
                if (pathMatcher.match(url, path)) {
                    bMatched = false;
                }
//                if (servletPath.contains(url)) {
//                    return false;
//                }
            }
        }
        
        if (bMatched) {
            for (String method : notAllowedMethods) {
                if (method.toUpperCase().equals(request.getMethod().toUpperCase())) {
                    bMatched = false;
                }
            }
        }
        return bMatched;
    }
}